<template>
  <div class="box" @click="freshDate">
    <div class="infobox">
      <div class="sidebar">
        <pre><div class="el-icon-message"> 消息中心</div></pre>
        <ul class="list">
          <li>购物信息</li>
          <li>举报信息</li>
          <li>回复我的</li>
          <router-link v-if="goodsId !== undefined" :to="{ path: '/shopping/chat', query: { userId ,goodsId} }">
            <li>好友列表</li>
          </router-link>
          <router-link v-else :to="{ path: '/shopping/chat', query: { userId } }">
            <li>好友列表</li>
          </router-link>
          <li class="active">换购消息</li>
        </ul>
      </div>
      <!-- 换购者-购买者 -->
      <div v-if="OwnerGoodsFrom.goodsOwner === otherUserFrom.username">
        <el-card v-if="OwnerGoodsFrom.goodsMessage == '换购中'" class="title">
          <p class="p2">换购消息(换购中)</p>
          <span v-if="OwnerGoodsFrom.chatFlag === 1 && OwnerGoodsFrom.goodsOwner === otherUserFrom.username" class="exchange-goods">
            正在交谈的物品：{{ OwnerGoodsFrom.goodsName }}
            <el-button v-if="OwnerGoodsFrom.goodsBuyer === selfUserFrom.username" size="mini" @click="closeExchangeGoods">取消换购</el-button>
          </span>
        </el-card>
        <el-card v-else-if="OwnerGoodsFrom.goodsMessage == '换购已取消'" class="title">换购消息(换购已取消)</el-card>
        <el-card v-else-if="OwnerGoodsFrom.goodsMessage == '换购成功'" class="title">
          <p class="p2">换购消息(换购成功)</p>
          <el-button class="btn" @click="goQueryPage">前往订单页面查看</el-button>
        </el-card>
        <el-card v-else class="title">换购消息(无)</el-card>
      </div>
      <!-- 物品所属者 -->
      <div v-else-if=" OwnerGoodsFrom.goodsBuyer === otherUserFrom.username">
        <el-card v-if="OwnerGoodsFrom.goodsMessage == '换购中'" class="title">
          <p class="p2">换购消息(换购中)</p>
          <span v-if="OwnerGoodsFrom.chatFlag === 1 && OwnerGoodsFrom.goodsBuyer === otherUserFrom.username" class="exchange-goods">
            正在交谈的物品：{{ OwnerGoodsFrom.goodsName }}
          </span>
        </el-card>
        <el-card v-else-if="OwnerGoodsFrom.goodsMessage == '换购已取消'" class="title">换购消息(换购已取消)</el-card>
        <el-card v-else-if="OwnerGoodsFrom.goodsMessage == '换购成功'" class="title">
          <p class="p2">换购消息(换购成功)</p>
          <el-button class="btn" @click="goQueryPage">前往订单页面查看</el-button>
        </el-card>
        <el-card v-else class="title">换购消息(无)</el-card>
      </div>
      <!-- 无相关的用户 -->
      <div v-else>
        <el-card class="title">换购消息(无)</el-card>
      </div>
      <el-card class="chat">
        <div class="title">
          <span class="p">近期消息</span>
          <div class="line" />
          <span class="chatuser">{{ otherUserFrom.username }}</span>
        </div>
        <ul class="userlist">
          <li v-if="userId == otherUserFrom.id" class="active">
            <img :src="otherUserFrom.avatar" alt="">
            <div class="username">{{ otherUserFrom.username }}</div>
          </li>
        </ul>
        <div class="chatbody">
          <div class="show" @click="ImgToBig">
            <!-- 图片放大的盒子 -->
            <img class="ImgBox" src="" alt="">
            <div v-for="(item,index) in chatList" :key="item.id">
              <div v-if="index === 0" class="time">双方友好沟通</div>
              <div v-if="item.userId === selfUserFrom.id && item.toId === otherUserFrom.id" class="self">
                <img class="avatar1" :src="selfUserFrom.avatar" alt="">
                <span v-if="item.message.length <= 500" class="chatinfo">
                  {{ item.message }}
                </span>
                <div v-else>
                  <img class="picImg" :src="item.message" alt="">
                </div>
              </div>
              <div v-if="item.userId === otherUserFrom.id && item.toId === selfUserFrom.id" class="other">
                <img class="avatar2" :src="otherUserFrom.avatar" alt="">
                <span v-if="item.message.length <= 500" class="chatinfo">
                  {{ item.message }}
                </span>
                <div v-else>
                  <img class="picImg" :src="item.message" alt="">
                </div>
              </div>
            </div>
            <!-- 交换订单 -->
            <el-card v-if="OwnerGoodsFrom.goodsExchange !== '无' && OwnerGoodsFrom.goodsBuyer === selfUserFrom.username" class="exchangeGoods">
              <img :src="selfGoodsFrom.goodsImg" alt="">
              <span>{{ selfGoodsFrom.goodsName }}</span>
              <img src="../../assets/交换.jpg" alt="">
              <img :src="OwnerGoodsFrom.goodsImg" alt="">
              <span>{{ OwnerGoodsFrom.goodsName }}</span>
              <button @click="refuse">取消</button>
            </el-card>
            <el-card v-else-if="OwnerGoodsFrom.goodsExchange !== '无' && OwnerGoodsFrom.goodsBuyer === otherUserFrom.username" class="exchangeGoods">
              <img :src="selfGoodsFrom.goodsImg" alt="">
              <span>{{ selfGoodsFrom.goodsName }}</span>
              <img src="../../assets/交换.jpg" alt="">
              <img :src="OwnerGoodsFrom.goodsImg" alt="">
              <span>{{ OwnerGoodsFrom.goodsName }}</span>
              <button @click="refuse">拒绝</button>
              <button @click="agree">同意</button>
            </el-card>
          </div>
          <hr style="background-color:#ced0da; height:1px; border:none;">
          <div class="send">
            <!-- <div v-if="OwnerGoodsFrom.chatFlag === 1 &&OwnerGoodsFrom.goodsOwner === otherUserFrom.username" class="el-icon-circle-plus" @click="openSelfGoods" /> -->
            <!-- 发送换购 -->
            <img v-if="OwnerGoodsFrom.chatFlag === 1 &&OwnerGoodsFrom.goodsOwner === otherUserFrom.username" class="icon-exchange" src="../../assets/交换2.jpg" alt="" @click="openSelfGoods">
            <!-- 发送照片 -->
            <el-upload
              action="http://localhost:8088/chat"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <div class="el-icon-picture" />
            </el-upload>
            <!-- 发送表情 -->
            <div class="emoji">
              <img src="../../assets/微笑.jpg" alt="" @click="emojiShow">
            </div>
            <div class="emojiBox">
              <span v-for="(item,index) in emoji" :key="index" @click="chooseEmoji(index)">{{ emoji[index] }}</span>
            </div>
            <ul v-show="isShow" class="selfgoods">
              <!-- eslint-disable-next-line vue/no-use-v-if-with-v-for -->
              <li v-for="item in goodsList" v-if="item.goodsOwner === selfUserFrom.username && item.goodsExchange === '无'" :key="item.goodsId">
                <img :src="item.goodsImg" :alt="item.goodsName" :title="item.goodsId" @click="chooseGoods">
              </li>
            </ul>
            <textarea v-if="text.length <= 500" v-model.trim="text" maxlength="500" rows="10" @keyup.enter.prevent="addmessage" @keyup="changebtn" />
            <img v-else class="picImg" :src="text">
            <span class="count">{{ count }}/500</span>
            <el-button @click="addmessage">发送</el-button>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import axios from 'axios'
import userApi from '@/api/userManage'
import chatApi from '@/api/chatManage'
import goodsApi from '@/api/goodsManage'
export default {
  data() {
    return {
      otherUserFrom: {},
      selfUserFrom: {},
      chatList: {},
      goodsList: [],
      OwnerGoodsFrom: {},
      selfGoodsFrom: {},
      selfGoodsList: [],
      text: "",
      userId: this.$route.query.userId,
      goodsId: this.$route.query.goodsId,
      oldScrollTop: 0,
      scrollFlag: true,
      Intervall: null,
      count: 0,
      isShow: false,
      emoji: ['😀', '😁', '😂', '😃', '😄', '😅', '😆', '😉', '😊', '😋', '😎', '😍', '😘', '😗', '😙', '😚', '😇', '😐', '😑', '😶', '😏', '😣', '😥', '😮', '😯', '😪', '😫', '😴', '😌', '😛', '😜', '😝', '😒', '😓', '😔', '😕', '😲', '😷', '😖', '😞', '😟', '😤', '😢', '😭', '😦', '😧', '😨', '😬', '😰', '😱', '😳', '😵', '😡', '😠', '💘', '❤', '💓', '💔', '💕', '💖', '💗', '💜', '💝', '💞', '💟', '❣', '💪', '👈', '👉', '☝', '👆', '👇', '✌', '✋', '👌', '👍', '👎', '✊', '👊', '👋', '👏', '👐', '✍', '🍇']
    }
  },
  computed: {
    ...mapGetters([
      'id',
      'name'
    ])
  },
  mounted() {
    this.getUpdataData()
    document.querySelector('.show').addEventListener('scroll', this.scrolling)
    this.scrollToBottom()
  },
  created() {
    setTimeout(this.render, 50)
  },
  methods: {
    // 选择表情
    chooseEmoji(index) {
      console.log(index)
      const emojiBox = document.querySelector('.emojiBox')
      this.text += this.emoji[index]
      emojiBox.style.display = 'none'
    },
    // 表情包盒子
    emojiShow() {
      const emojiBox = document.querySelector('.emojiBox')
      if (emojiBox.style.display === 'block') {
        emojiBox.style.display = 'none'
      } else {
        emojiBox.style.display = 'block'
      }
    },
    // 图片放大
    ImgToBig(e) {
      console.log(e.target.src)
      if (e.target._prevClass === 'picImg' || e.target._prevClass === 'ImgBox') {
        const ImgBox = document.querySelector('.ImgBox')
        ImgBox.style.display = 'block'
        ImgBox.src = e.target.src
      } else {
        const ImgBox = document.querySelector('.ImgBox')
        ImgBox.style.display = 'none'
      }
    },
    // 前往订单页面
    goQueryPage() {
      this.$router.push('/shopping/query')
    },
    // blob转码为base64
    BlobToBase64(image) {
      image.onload = () => {
        const canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        const context = canvas.getContext('2d')
        context.drawImage(image, 0, 0, image.width, image.height)
        const obj = {
          "userId": this.selfUserFrom.id,
          "toId": this.otherUserFrom.id,
          "message": " ",
          "talkId": 1
        }
        obj.message = canvas.toDataURL()
        this.text = canvas.toDataURL()// 图片的base64地址
        this.$set(obj, "message", obj.message)
        chatApi.updateChat(obj)
        console.log(obj)
      }
    },
    // 发送图片
    handleAvatarSuccess(res, file) {
      // bolb转base64
      const image = new Image() // 新建一个img标签（还没嵌入DOM节点)
      image.src = URL.createObjectURL(file.raw)
      this.BlobToBase64(image)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 同意
    agree() {
      this.$confirm(`您同意该换购订单吗 ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '换购成功！'
        })
        this.$set(this.OwnerGoodsFrom, "goodsMessage", '换购成功')
        this.$set(this.OwnerGoodsFrom, "goodsFlag", 1)
        this.$set(this.OwnerGoodsFrom, "chatFlag", 0)
        this.$set(this.OwnerGoodsFrom, "goodsExchange", this.selfGoodsFrom.goodsName)
        goodsApi.updateGoods(this.OwnerGoodsFrom)
        this.$set(this.selfGoodsFrom, "goodsMessage", '换购成功')
        this.$set(this.selfGoodsFrom, "goodsExchange", this.OwnerGoodsFrom.goodsName)
        this.$set(this.selfGoodsFrom, "goodsCount", 1)
        this.$set(this.selfGoodsFrom, "goodsFlag", 1)
        this.$set(this.selfGoodsFrom, "goodsBuyer", this.OwnerGoodsFrom.goodsOwner)
        goodsApi.updateGoods(this.selfGoodsFrom)
        console.log(this.selfGoodsFrom)
        setTimeout(function() {
          const exchangeGoods = document.querySelector(".exchangeGoods")
          exchangeGoods.style.display = 'none'
        }, 50)
        setTimeout(this.render, 50)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    // 不同意
    refuse() {
      this.$set(this.OwnerGoodsFrom, "goodsExchange", '无')
      goodsApi.updateGoods(this.OwnerGoodsFrom)
      setTimeout(this.render, 50)
    },
    // 刷新数据
    freshDate() {
      setTimeout(this.render, 50)
      console.log(this.OwnerGoodsFrom.goodsExchange)
      if (this.OwnerGoodsFrom.goodsExchange !== '无' && this.OwnerGoodsFrom.goodsMessage !== '换购成功') {
        goodsApi.getGoodsById(this.OwnerGoodsFrom.goodsExchange).then(response => {
          this.selfGoodsFrom = response.data
          console.log(this.selfGoodsFrom.goodsName)
        })
        const exchangeGoods = document.querySelector(".exchangeGoods")
        exchangeGoods.style.display = 'block'
      } else if (this.OwnerGoodsFrom.goodsMessage === '换购成功') {
        const exchangeGoods = document.querySelector(".exchangeGoods")
        exchangeGoods.style.display = 'none'
        setTimeout(function() {
          this.isShow = false
          const selfgoods = document.querySelector(".selfgoods")
          selfgoods.style.opacity = 0
        }, 50)
      }
    },
    // 选择物品
    chooseGoods(e) {
      this.$confirm(`选择${e.target.alt}进行换购吗 ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '操作成功'
        })
        // console.log(e.target.title)
        this.$set(this.OwnerGoodsFrom, "goodsExchange", e.target.title)
        goodsApi.updateGoods(this.OwnerGoodsFrom)
        console.log(this.OwnerGoodsFrom)
        goodsApi.getGoodsById(e.target.title).then(response => {
          this.selfGoodsFrom = response.data
        })
        const exchangeGoods = document.querySelector(".exchangeGoods")
        exchangeGoods.style.display = 'block'
      }).catch(() => {
      })
    },
    // 取消换购
    closeExchangeGoods() {
      this.$confirm(`您确认要取消换购吗 ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$set(this.OwnerGoodsFrom, "chatFlag", 0)
        this.$set(this.OwnerGoodsFrom, "goodsCount", 0)
        this.$set(this.OwnerGoodsFrom, "goodsBuyer", '暂无')
        this.$set(this.OwnerGoodsFrom, "goodsMessage", '换购已取消')
        goodsApi.updateGoods(this.OwnerGoodsFrom)
        this.$router.push({ path: '../shopping/exchange', query: { userId: this.userId }})
        window.location.reload()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消换购'
        })
      })
    },
    // 获取交谈对象的物品
    getOwnerGoods() {
      goodsApi.getGoodsById(this.goodsId).then(response => {
        this.OwnerGoodsFrom = response.data
        console.log(this.OwnerGoodsFrom)
      })
    },
    // 自己的物品列表
    openSelfGoods() {
      const selfgoods = document.querySelector(".selfgoods")
      if (this.isShow) {
        this.isShow = false
        selfgoods.style.opacity = 0
      } else {
        this.isShow = true
        selfgoods.style.opacity = 1
      }
    },
    // 渲染函数
    render() {
      this.getOtherUserFromByUserId(this.userId)
      this.getSelfUserFromByUserId(this.id)
      this.getAllChat()
      this.getAllGoods()
      if (this.goodsId !== undefined) {
        this.getOwnerGoods()
      }
    },
    // 获取所有的物品信息
    getAllGoods() {
      goodsApi.getAllGoods().then(response => {
        this.goodsList = response.data
        console.log(this.goodsList)
      })
    },
    // 按钮变色
    changebtn() {
      if (this.text !== '') {
        const textarea = document.querySelector('textarea')
        const btn = document.querySelector('.el-button')
        console.log(btn)
        console.log(textarea)
        btn.style.backgroundColor = '#1389bf'
      } else {
        const btn = document.querySelector('.el-button')
        btn.style.backgroundColor = '#fff'
      }
      this.count = this.text.length
    },
    // 滚轮到底部
    scrolling() {
      const scrollTop = document.querySelector('.show').scrollTop
      // 更新——滚动前，滚动条距文档顶部的距离
      const scrollStep = scrollTop - this.oldScrollTop
      this.oldScrollTop = scrollTop
      // 判断当前是向上or向下滚动
      if (scrollStep < 0) {
        // 向上
        console.log('正在向上滚动')
        this.scrollFlag = false
      } else {
        console.log('正在向下滚动')
        this.scrollFlag = true
      }
    },
    getUpdataData() {
      // 定时获取后台返回数据
      this.Interval = setInterval(() => {
        axios('http://localhost:8088/chat/time').then((res) => {
          // 更新数据
          this.xxx = res.data
          // 当数据更新完毕清除定时器
          if (res.code === 0) {
            clearInterval(this.Interval)
          }
        })
        // 调用保持滚动条方法（这一步也可以在updated生命周期调用）
        if (this.scrollFlag) {
          this.scrollToBottom()
        }
      }, 1000)
    },
    scrollToBottom() {
      this.$nextTick(() => {
        var container = this.$el.querySelector('.show')
        container.scrollTop = container.scrollHeight
      })
    },
    // 发送消息
    addmessage(e) {
      if (this.text !== '' && this.text !== '\n') {
        const obj = {
          "userId": this.selfUserFrom.id,
          "toId": this.otherUserFrom.id,
          "message": " ",
          "talkId": 1
        }
        console.log(obj)
        chatApi.addChat(obj).then(response => {
          console.log(obj)
        })
        this.$set(obj, "message", this.text)
        chatApi.updateChat(obj)
        this.text = ""
        setTimeout(this.getAllChat, 200)
      }
    },
    // 获取对话信息
    getAllChat() {
      chatApi.getChatGroupByTime().then(response => {
        this.chatList = response.data
        console.log(this.chatList)
      })
    },
    // 获取对方用户信息
    getOtherUserFromByUserId(userId) {
      userApi.getUserById(userId).then(response => {
        this.otherUserFrom = response.data
        console.log(this.otherUserFrom)
      })
    },
    // 获取自己的用户信息
    getSelfUserFromByUserId(id) {
      userApi.getUserById(id).then(respose => {
        this.selfUserFrom = respose.data
        console.log(this.selfUserFrom)
      })
    }
  }
}
</script>

<style src="../../styles/chat.css">

</style>
